const config = require('../../config');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: null,
    imglist: null,
    djs: { d: 0, h: 0, m: 0, s: 0},
    czstate: 0,
    wxInfo: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  bindGetUserInfo: function (e) {
    var self = this;
    app.getWxInfo((err, wxInfo) => {
      if (!err) {
        self.setData({
          wxInfo: wxInfo
        });
      }
    });
  },
  onLoad: function (options) {
    wx.showLoading();
    var _this = this;
    if (app.globalData.userInfo){
      this.loadinfo(options.orderCode);
    }else{
      app.getUserInfo((err, wxInfo) => {
        _this.loadinfo(options.orderCode);
      });
    }

    if (!app.globalData.wxInfo) {
      app.getWxInfo((err, wxInfo) => {
        if (err) {
          _this.setData({
            wxInfo: false
          });
        }
      });
    }
  },
  loadinfo: function (orderCode){
    var _this = this;

    wx.request({
      url: config.groupinfoUrl,
      data: {
        orderCode: orderCode
      },
      success: function (res) {
        console.log(res.data.data.list[0]);
        wx.hideLoading();
        if (res.data && res.data.data) {
          if(!res.data.data.list.length){
            wx.showToast({
              icon: "none",
              title: '当前团购不存在或已解散',
            })
            var pages = getCurrentPages();
            if (pages.length > 1) {
              //上一个页面实例对象
              var prePage = pages[pages.length - 2];
              //关键在这里
              prePage.onLoad()

              wx.navigateBack({
                delta: 1
              })
            }else{
              setTimeout(function () {
                // wx.switchTab({
                //   url: '../index/index'
                // })
                wx.navigateTo({
                  url: '../index/index'
                })
              }, 2000)
            }
            
            return false;
          }

          _this.setData({
            detail: res.data.data.list[0]           
          });

          _this.loadjginfo(_this.data.detail.styoeCode);
          _this.groupendtime();
          _this.gettzinfo();          
        } else {
          wx.showToast({
            icon: 'none',
            title: '网络异常',
          })
        }
      }
    })    
  }
  ,
  loadjginfo(institutionCode){
    var _this = this;
    wx.request({
      url: config.getgroupdetailUrl,
      data: {
        code: institutionCode
      },
      success: function (res) {
        if (res.data && res.data.data) {
          _this.setData({
            jigouinfo: res.data.data.list[0]
          });

          _this.loadpicimg(_this.data.jigouinfo.institutionCode);
        } else {
          wx.showToast({
            icon: 'none',
            title: '网络异常',
          })
        }
      }
    })
  }
  ,
  loadpicimg: function (institutionCode) {
    var _this = this;
    wx.request({
      url: config.imglistUrl,
      data: {
        institutionCode: institutionCode,
        pageNum: 9999
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data && res.data.data) {
          var imglist = _this.tqimgurl(res.data.data.list);
          _this.setData({
            imglist: imglist
          });
        }
      }
    })
  },
  gettzinfo: function (){
    var _this = this;
    wx.request({
      url: config.groupinfoUrl,
      data: {
        orderCode: _this.data.detail.orderCode,
        qxStatis: 1
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data && res.data.data) {
          _this.setData({
            tzinfo: res.data.data.list[0],
            czstate: res.data.data.list[0].Initiator == app.globalData.userInfo.openId?1:2
          });
          //团购列表
          _this.getuserlist();
        }
      }
    })
  },
  getuserlist:function(){
    var _this = this;
    wx.request({
      url: config.groupuserlistUrl,
      data: {
        wxOpenId: app.globalData.userInfo.openId,
        orderCode: _this.data.detail.orderCode,
        isPay: 2,
        refund: 1,
        sysPay: 1,
      },
      success: function (res) {
        // console.log(res);        
        if (res.data && res.data.data) {
          var list = res.data.data.list;
          _this.setData({
            ptuserlist: list
          });
          if(list.length){
            var u = null;
            for(var i = 0; i<list.length; i++){
              u = list[i];
              if (u.openId == app.globalData.userInfo.openId && u.openId != _this.data.tzinfo.Initiator){
                _this.setData({
                  czstate: 3
                });
                break;
              }
            }
          }
        }
      }
    })
  },
  shouimglist: function () {
    wx.previewImage({
      urls: this.data.imglist
    });
  },
  tqimgurl: function(arrdata){
    var imglist = [];
    for(var i = 0; i<arrdata.length; i++){
      imglist.push("https://www.sharekq.cn/"+arrdata[i].pic);
    }
    return imglist;
  },
  hideshare: function(){
    this.setData({
      showSharet: false
    });
  },
  shareshow: function(){
    return false;
    var _this = this;
    if(this.data.shareimg){
      this.setData({
        showSharet: true
      });
    }else{
      this.ctx = wx.createCanvasContext('customCanvas'); 

      this.setData({
        showSharet: true,
        loadshareinfo: true
      });

      wx.getImageInfo({
        src: "https://www.sharekq.cn/" + _this.data.jigouinfo.otherPic1,
        success(res) {
          _this.ctx.drawImage(res.path, 0, 0, 720, 1280);

          _this.loadqrcode(function(url){
            wx.getImageInfo({
              src: url,
              success(res) {
                _this.ctx.drawImage(res.path, 527, 1030, 177, 177);
                _this.ctx.draw();

                wx.canvasToTempFilePath({
                  canvasId: 'customCanvas',
                  success(res) {
                    _this.setData({
                      loadshareinfo: false,
                      shareimg: res.tempFilePath
                    });

                    wx.authorize({
                      scope: 'scope.writePhotosAlbum',
                      success() {
                        wx.saveImageToPhotosAlbum({
                          filePath: res.tempFilePath,
                          success() {
                            wx.showToast({
                              title: '图片已自动保存'
                            })
                          }
                        })
                      }
                    })
                  }
                }, this);
              }
            });
          });
        }
      })
    }
  },
  loadqrcode: function (callback){
    wx.request({
      url: config.getqrcodeUrl,
      data: {
        code: this.data.jigouinfo.code,
         UrlCode: "",
         page: "pages/groupinfo/index",
         fxopenId: app.globalData.userInfo.openId,
        orderCode: this.data.detail.orderCode,
         wxType: 1
      },
      success: function (res) {
        console.log(res);
        callback(res.data);
      }
    });
  },
  groupendtime(){
    var self = this;
    setInterval(function () {
      let nowTime = new Date(self.data.detail.endTime) - new Date;
      let minutes = checkTime(parseInt(nowTime / 1000 / 60 % 60, 10));//计算剩余的分钟
      let seconds = checkTime(parseInt(nowTime / 1000 % 60, 10));//计算剩余的秒数        

      let days = parseInt(nowTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数
      let hours = parseInt(nowTime / 1000 / 60 / 60 % 24, 10); //计算剩余的小时

      // if (days > 0) {
      //   djs = days + "天 " + hours + ":" + minutes + ":" + seconds;
      // } else {
      //   let hours = parseInt(nowTime / (1000 * 60 * 60), 10);
      //   djs = hours + "小时" + minutes + "分" + seconds;
      // }
 
      self.setData({
        djs: { d: days, h: hours, m: minutes, s: seconds }
      });
    }, 1000);

    function checkTime(i) { //将0-9的数字前面加上0，例1变为01
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
  },
  //参与拼团
  cyptcreateorder : function(){
    var self = this;
    wx.showModal({
      title: '',
      content: '您确定要参加此团购吗？',
      cancelText: "不要",
      confirmColor: "#40AFFE",
      success: function (res) {
        if (res.confirm) {
          self.cygroup();
        }
      }
    })
  },
  cygroup: function () {
    wx.showLoading();
    var self = this;
    wx.request({
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        orderCode: self.data.tzinfo.orderCode,
        openId: app.globalData.userInfo.openId,
        pic: app.globalData.wxInfo.avatarUrl
      },
      method: "POST",
      url: config.cygroupUrl,
      success: res => {
        wx.hideLoading();
        if (res && res.data) {
          if (res.data.status == 0 || res.data.status == -4) {
            wx.showToast({
              icon: "SUCCESS",
              title: res.data.msg,
            });
            self.grouppayment(res.data.data.tradeCode);
          } else {
            wx.showToast({
              icon: "none",
              title: res.data.msg,
            })
          }
        }
      }
    })
  },
  //调用支付
  grouppayment: function (orderCode) {
    wx.showLoading();
    var _this = this;
    wx.request({
      header: {
        token: config.token,
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        openId: app.globalData.userInfo.openId,
        fee: _this.data.tzinfo.ptPrice,
        applyName: "商品支付",
        applyNum: orderCode
      },
      method: "POST",
      url: config.groupPaymentUrl,
      success: res2 => {
        wx.hideLoading();
        if (res2.data) {
          //调用支付接口
          wx.requestPayment({
            timeStamp: res2.data.timeStamp,
            nonceStr: res2.data.nonceStr,
            package: res2.data.package,
            signType: res2.data.signType,
            paySign: res2.data.paySign,
            success: function (payres) {
              if (payres.errMsg = "requestPayment:ok") {
                // _this.saveFormid(paymentprom.prepay_id);
                _this.loadinfo(_this.data.detail.orderCode);
              }
            }
          })
        } else {
          wx.showToast({
            icon: "none",
            title: "支付请求失败",
          })
        }
      }
    });
  },
  //团长退团
  groupcancel: function(){
    var _this = this;
    if (!_this.data.ptuserlist || !_this.data.ptuserlist.length){    
      wx.showModal({
        title: '',
        content: '您确定要解散此团购吗？',
        cancelText: "不要",
        confirmColor: "#40AFFE",
        success: function (res) {
          if (res.confirm) {
            wx.showLoading();
            wx.request({
              url: config.groupcancelUrl,
              data: {
                orderCode: _this.data.detail.orderCode,
                Initiator: app.globalData.userInfo.openId,
                status: -1
              },
              success: function (res) {
                wx.hideLoading();
                if(res.data){
                  if(res.data.status == 0){
                    _this.loadinfo(_this.data.detail.orderCode);
                  }else{
                    wx.showToast({
                      icon: 'none',
                      title: res.data.msg
                    })
                  }
                }
              }
            });
          }
        }
      })
    } else if (_this.data.ptuserlist.length > 1){
      wx.showToast({
        icon: 'none',
        title: '拼团已开始无法解散'
      })
    }else{
      var u = _this.data.ptuserlist[0];
      if (u.openId == app.globalData.userInfo.openId && u.openId == _this.data.tzinfo.Initiator && u.sysPay == "1") {
        _this.payrefund(u);
      }else{
        wx.showToast({
          icon: 'none',
          title: '拼团已开始无法解散'
        })
      }
    }
  },
  //用户退团
  userefund: function(){
    var _this = this;
    wx.showModal({
      title: '',
      content: '您确定要退出团购吗？',
      cancelText: "不要",
      confirmColor: "#40AFFE",
      success: function (res) {
        if (res.confirm) {
          var u = null;
          var list = _this.data.ptuserlist;
          for (var i = 0; i < list.length; i++) {
            u = list[i];
            if (u.openId == app.globalData.userInfo.openId && u.openId != _this.data.tzinfo.Initiator) {
              _this.payrefund(u);
              break;
            }
          }
        }
      }
    });
  },
  payrefund: function(payinfo){
    wx.showLoading({
      title: '申请退款中'
    });
    var _this = this;
    wx.request({
      url: config.payrefund,
      data: {
        openId: app.globalData.userInfo.openId,
        fee: payinfo.ptPrice,
        transaction_id: payinfo.wxTradeCode ,
        applyName: '',
        applyNum: ''
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data) {
          if (res.data && res.data[0].result_code == "SUCCESS") {
            _this.loadinfo(_this.data.detail.orderCode);
          } else {
            wx.showToast({
              icon: 'none',
              title: res.data[0].err_code_des ? res.data[0].err_code_des:"请求失败"
            })
          }
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (option) {
    return  {
      title: this.data.detail.ptRemark,
      imageUrl: "https://www.sharekq.cn/" + this.data.jigouinfo.otherPic1
    }
  }
})